package com.carmanage.service;

import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.carmanage.dao.UserDao;
import com.carmanage.domain.Page;
import com.carmanage.domain.Role;
import com.carmanage.domain.User;

@Component
@Service
public class UserService {
    
	
	@Resource
	private UserDao userDao;
	
	private List<User> users;
	
    private SessionFactory sessionFactory;
	
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	public int addUser(User user) {
		// TODO Auto-generated method stub
	    try{
	    	userDao.addUser(user);
	    	System.out.println("userDao执行在userServiceimpl");
	    	return 1;
	    	
	    }catch(HibernateException e){
	    	return 0 ;
	    }
		
	}
	public List<User> findAllUser() {
		// TODO Auto-generated method stub
	     users = userDao.findAllUser();
		 return users;
	}
	public User findUserByName(String name) {
		// TODO Auto-generated method stub
		User user = userDao.findUserByName(name);
		return user;
	}
	public int deleteUserById(int i) {
		// TODO Auto-generated method stub
		int deleteResult = userDao.deleteUserById(i);
		return 1;
	}
	public int findUser(String username, String password, int roleid) {
		// TODO Auto-generated method stub
		User user = userDao.findUser(username,password);
		if(user != null){
			Session session = sessionFactory.openSession();
			Iterator<Role> iterator = user.getRoles().iterator();
			while(iterator.hasNext()){
			   Integer itera = (Integer) iterator.next().getRoleid();
			   if(roleid == itera.intValue()){
				   session.close();
				   return 1; 
			   }
			}
			session.close();
			return 2;
		}else 
		    return 0;
	}

	public int findAllUserRecord() {
		// TODO Auto-generated method stub
		int AllUserRecord = userDao.findAllUserRecord();
		return AllUserRecord;
	}

	public List<User> findUserByPage(Page userPage) {
		// TODO Auto-generated method stub
		List<User> usersByPage = userDao.findUserByPage(userPage);
		return usersByPage;
	}
    
}
